package util

import (
	"archive/zip"
	"fmt"
	"io"
	"os"
)

func Zip(src []string, dest string) error {
	if len(src) == 0 || dest == "" {
		return fmt.Errorf("src or dest is empty")
	}

	f, err := os.Create(dest)
	if err != nil {
		return fmt.Errorf("create dest file[%s] fail, %v", dest, err)
	}
	defer func() { _ = f.Close() }()

	w := zip.NewWriter(f)
	defer func() {
		_ = w.Close()
	}()

	for _, s := range src {
		sf, err := os.Open(s)
		if err != nil {
			return fmt.Errorf("open source file[%s] fail, %v", s, err)
		}
		defer func() { _ = sf.Close() }()

		sw, err := w.Create(GetFileName(s))
		if err != nil {
			return fmt.Errorf("create source file[%s] writer fail, %v", s, err)
		}

		if _, err := io.Copy(sw, sf); err != nil {
			return fmt.Errorf("write source file[%s] fail, %v", s, err)
		}
	}

	return nil
}
